package com.qianxun.framework.web.util;

import com.qianxun.framework.common.util.DateUtil;
import com.qianxun.module.base.exception.ServiceInterruptionException;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author: huwei
 * @date: 2019/12/17 16:49
 * @version: 1.0.0
 */
public class RequestParameterUtil {
    private RequestParameterUtil(){}

    /**
     * 解析layui提交的时间格式字符串
     * 格式：yyyy-MM-dd HH:mm:ss - yyyy-MM-dd HH:mm:ss
     * @param timeLimit 时间格式字符串
     * @return 字符串不为空，且格式正确，返回开始和结束时间，反之null
     * @throws ServiceInterruptionException 时间格式解析失败
     */
    public static final DateTimeParameter parseLayuiTimeLimit(String timeLimit) throws ServiceInterruptionException {
        if(StringUtils.isEmpty(timeLimit)){
            return new DateTimeParameter();
        }
        final String layuiTimePattern = " - ";
        if(timeLimit.indexOf(layuiTimePattern) == -1){
            return new DateTimeParameter();
        }
        final int length = 2;
        String[] times = timeLimit.split(layuiTimePattern);
        if(times.length != length){
            return new DateTimeParameter();
        }
        try {
            Date start = DateUtil.parse(times[0]);
            Date end = DateUtil.parse(times[1]);
            return new DateTimeParameter().setStart(start).setEnd(end);
        }catch (Throwable e){
        }
        return new DateTimeParameter();
    }

    /**
     * 时间参数
     */
    @Data
    @Accessors(chain = true)
    public static final class DateTimeParameter{
        private Date start;
        private Date end;
    }
}
